//
//  ECDHomeViewController.m
//  XTCloud
//
//  Created by QA on 16/9/20.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "ECDHomeViewController.h"
#import "GETableView.h"

#import "ECDHomeViewCell.h"
#import "EnterpriseDiskFilerCell.h"
#import "NSDictionary+DataFormat.h"
#import "ServiceConnect.h"

#import "FileSizeFormatHelper.h"
#import "FileTypeIcon.h"
#import "DownLoadHandle.h"
#import "PreviewFileHelper.h"

@interface ECDHomeViewController ()

@property (nonatomic,strong) IBOutlet GETableView *tableView;
@property (strong, nonatomic) NSMutableArray *resultData;
@property (nonatomic,assign) NSInteger orderContentState;//0加载中，1未找到数据，2加载失败，3加载成功

@end

@implementation ECDHomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle:@"企业云盘"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    
    self.tableView.tableFooterView= [[UIView alloc] init];
    [self getNetWorkExternalData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark 网络获取数据

- (void)getNetWorkExternalData
{
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_MobileNetDiskSame" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //显示数据处理
        [self.resultData removeAllObjects];
        if(result.resultArray && result.resultArray.count>0){
            [self.resultData addObjectsFromArray:result.resultArray];
            self.orderContentState = 3;
        } else {
            self.orderContentState = 1;
        }
        [self.tableView reloadData];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
    }];
    
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0) return 0.000001f;
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    if(section == 0) return view;
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    lable.text = @"最新上传文件";
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:0.8];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0) return 1;
    else if(section == 1) {
        NSInteger count = self.resultData.count;
        return count > 0 ? count : 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //九宫格
    if(indexPath.section == 0){
        NSString *keyValue = [NSString stringWithFormat:@"ad-%ld-%ld",indexPath.section,indexPath.row];
        ECDHomeViewCell *cell = [self.tableView getCellViewKey:keyValue];
        if (!cell) {
            cell = [[ECDHomeViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:keyValue];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setNavigationController:self.navigationController];
            [self.tableView setCellView:cell key:keyValue];
        }
        return cell;
    }
    
    if (self.orderContentState == 3) {
        //最新文件
        static NSString *CellIdentifierOne = @"EnterpriseDiskFilerCell";
        EnterpriseDiskFilerCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
        if (!cell){
            cell = [[EnterpriseDiskFilerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
            
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(70, 69.5, SuperWidth-70, 0.5)];
            lineView.backgroundColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:0.8];
            [cell.contentView addSubview:lineView];
        }
        
        NSDictionary *mDictionary = [self.resultData objectAtIndex:indexPath.row];
        cell.titleLable.text = [mDictionary objectFormatStringForKey:@"名称"];
        cell.timeLable.text = [mDictionary objectFormatStringForKey:@"创建时间"];
        
        //图标设置
        NSString *iconString = [mDictionary objectFormatStringForKey:@"文件路径"];
        cell.iconImage.image = [FileTypeIcon setFileTypeIcon:iconString];
        
        //文件尺寸格式化
        NSString *fileSize = [mDictionary objectFormatStringForKey:@"文件大小"];
        fileSize = [FileSizeFormatHelper getFileSizeString:fileSize];
        cell.sizeLable.text = fileSize;
        
        //设置下载按钮
        cell.downButton.tag = indexPath.row;
        [cell.downButton addTarget:self action:@selector(downadJunctFile:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
        
    } else {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MTCClienterDetailHT"];
        cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 55);
        
        if(self.orderContentState == 0) {//加载进度条
            UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            act.center = CGPointMake(SuperWidth/2, 30.0f);
            act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
            act.hidesWhenStopped = YES;
            [act startAnimating];
            [cell.contentView addSubview:act];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        } else if(self.orderContentState == 1){//显示无数据提示
            UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
            label.text = @"暂无最新文件";
            label.font = [UIFont fontWithName:@"Arial" size:16];
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:label];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        } else if(self.orderContentState == 2){//显示失败提示
            UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
            label.text = @"加载失败，点击重试";
            label.font = [UIFont fontWithName:@"Arial" size:16];
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:label];
        }
        return cell;
    }
    
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    return [ECDHomeViewCell getCellHeight];
    
    if (indexPath.row >= self.resultData.count) return 56;
    return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1) {
        if(self.orderContentState == 2) {//加载失败执行
            self.orderContentState = 0;
            [self.tableView reloadData];
            [self getNetWorkExternalData];
            
        } else if(self.orderContentState == 3) { //加载成功
            [self previewJunctFile:indexPath.row];
        }
    }
}

#pragma mark Button Event

- (void)previewJunctFile:(NSInteger)index
{
    //预览文件
    NSDictionary *fileDictionary = [self.resultData objectAtIndex:index];
    NSString *fileName = [fileDictionary objectFormatStringForKey:@"名称"];
    NSString *filePath = [fileDictionary objectFormatStringForKey:@"文件路径"];
    
    //创建连接，预览文件
    PreviewFileHelper *preview = [[PreviewFileHelper alloc] init];
    [preview startPreviewExternalFile:filePath fileName:fileName];
}

- (void)downadJunctFile:(UIButton*)button
{
    //下载附件
    NSDictionary *fileDictionary = [self.resultData objectAtIndex:button.tag];
    NSString *fileName = [fileDictionary objectFormatStringForKey:@"名称"];
    NSString *filePath = [fileDictionary objectFormatStringForKey:@"文件路径"];
    
    //创建连接，下载文件
    DownLoadHandle *downLoad = [[DownLoadHandle alloc] init];
    [downLoad startDownExternalFile:filePath fileName:fileName];
}

@end
